package com.my.study.common.utils;

import com.my.study.dto.JwtUserDto;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * Security相关操作
 *
 * @author yidujun
 * @date 2022/8/4 13:18
 */
public final class SecurityUtils {

    private SecurityUtils() {
    }

    /**
     * 获取令牌进行认证
     *
     * @param request
     */
    public static void checkAuthentication(HttpServletRequest request) {
        // 获取令牌并根据令牌获取登录认证信息
        Authentication authentication = JwtTokenUtils.getAuthenticationFromToken(request);
        // 设置登录认证信息到上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }


    /**
     * 获取当前用户名
     *
     * @return 用户名
     */
    public static String getUsername() {
        return getUsername(getAuthentication());
    }

    /**
     * 获取用户名
     *
     * @return 用户名
     */
    public static String getUsername(Authentication authentication) {
        String username = null;
        if (authentication != null) {
            JwtUserDto jwtUserDto = JwtTokenUtils.getUserFromAuthentication(authentication);
            username = jwtUserDto.getMyUserEntity().getUserName();
        }
        return username;
    }

    /**
     * 获取当前登录信息
     *
     * @return Authentication
     */
    public static Authentication getAuthentication() {
        if (SecurityContextHolder.getContext() == null) {
            return null;
        }

        return SecurityContextHolder.getContext().getAuthentication();
    }
}
